package core.subcontrollers;

import controllers.FieldController;
import ie.FieldBoard;
import ie.PlayerBoard;
import ie.Shaker;
import boundary.UI;
import dto.Field;
import dto.Player;
import entity.Account;
import entity.fields.Jail;
import entity_controllers.options.BuyHouseOption;
import entity_controllers.options.SellHouseOption;
import entity_controllers.options.ShakeMoveOption;
import entity_controllers.options.effects.JailEffect;
import entity_controllers.options.effects.MoveEffect;

public class PlayerController {

	public static boolean payAmount(Player player, Player creditor, int amount) {
		
		Account account = (Account) player.getAccount();
		
		while(!account.hasAfford(amount) && account.hasBuildings()){
			SubController.sellHouse(player);
		}		
		
		if (player.getAccount().hasAfford(amount)) {
			player.getAccount().subBalance(amount);
			
			if (creditor != null)
				creditor.getAccount().addBalance(amount);
		
			return true;
		}
		
		return false;
	}

	public static void setInJail(Player player, FieldBoard fieldBoard) {
	
		// find the Jail in the fieldBoard
		int jailIndex = 0;
		for (int f = 0; f < fieldBoard.getFields().length; f++) {
			if (fieldBoard.getField(f).getClass() == Jail.class && !((Jail) fieldBoard.getField(f)).isSendsToJail()) {
				jailIndex = f;
				break;
			}
		}
	
		// Move player to Jail Field
		player.setFieldIndex(jailIndex);
		UI.get().showPlayer(player);
	
		Account account = (Account) player.getAccount();
	
		account.getOM().getOption(ShakeMoveOption.class).disable();
		account.getOM().getOption(BuyHouseOption.class).disable();
		account.getOM().getOption(SellHouseOption.class).disable();
	
		account.getEM().getOption(JailEffect.class).enable();
		account.getEM().getOption(MoveEffect.class).disable();
	
	}
	
	public static void movePlayerByDiceSum(Player player, FieldBoard fieldBoard, PlayerBoard playerBoard, Shaker shaker){
		int numberOfFields = fieldBoard.getFields().length;
		int diceSum = player.getDiceSum();
		int fieldIndex = player.getFieldIndex() + diceSum;
		
		boolean passedStart = false;
		if(diceSum > 0){
		
			passedStart = fieldIndex >= numberOfFields && player.getFieldIndex() > 0;
	
			fieldIndex %= numberOfFields;
		
		}
		else if(fieldIndex < 0)
			fieldIndex = numberOfFields + fieldIndex;
		
		player.setFieldIndex(fieldIndex);

		UI.get().showPlayer(player);

		if (passedStart) {
			player.getAccount().addBalance(Rules.PASSED_START_AMMOUND);
			UI.get().getMessage("Du passerede start og indkasserer " + Rules.PASSED_START_AMMOUND);
			UI.get().showPlayer(player);
		}

		Field newField = fieldBoard.getField(fieldIndex);
		FieldController fieldControler = newField.getFieldController();

		fieldControler.execute(player, newField, fieldBoard, playerBoard, shaker);
	}
}
